<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宠物狗图片上传</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        warning: '#F59E0B',
                        info: '#3B82F6',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-soft {
                box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
            }
            .transition-all-300 {
                transition: all 0.3s ease;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
    <header class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-2xl font-bold text-primary flex items-center">
                <i class="fa fa-paw mr-2"></i>宠物狗识别系统
            </h1>
            <nav>
                <ul class="flex space-x-6">
                    <li><a href="#" class="text-gray-600 hover:text-primary transition-colors">首页</a></li>
                    <li><a href="#upload" class="text-primary font-medium border-b-2 border-primary pb-1">图片上传</a></li>
                    <li><a href="#about" class="text-gray-600 hover:text-primary transition-colors">关于我们</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8">
        <section id="upload" class="max-w-3xl mx-auto bg-white rounded-xl shadow-soft p-6 md:p-8">
            <h2 class="text-xl md:text-2xl font-bold mb-6 text-gray-800">上传宠物狗图片</h2>
            
            <div class="mb-6">
                <p class="text-gray-600 mb-2">支持格式：JPEG、PNG、WEBP</p>
                <p class="text-gray-600 mb-2">文件大小：10KB - 8MB</p>
                <p class="text-gray-600">推荐分辨率：≥200×200px</p>
            </div>

            <!-- 文件上传区域 -->
            <div id="upload-area" class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-primary transition-all-300 cursor-pointer mb-6">
                <input type="file" id="file-input" accept="image/jpeg, image/png, image/webp" class="hidden"/>
                <i class="fa fa-cloud-upload text-4xl text-gray-400 mb-3"></i>
                <p class="text-gray-500 mb-2">点击或拖拽文件到此处上传</p>
                <p class="text-gray-400 text-sm">支持 JPG、PNG、WEBP 格式，最大 8MB</p>
            </div>

            <!-- 上传按钮 -->
            <div class="flex justify-center mb-6">
                <button id="upload-btn" class="bg-primary hover:bg-primary/90 text-white font-medium px-6 py-3 rounded-lg flex items-center shadow-md hover:shadow-lg transition-all-300 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    <i class="fa fa-paper-plane mr-2"></i>开始上传
                </button>
            </div>

            <!-- 进度条 -->
            <div id="progress-container" class="hidden mb-6">
                <div class="flex justify-between text-sm text-gray-600 mb-1">
                    <span>上传进度</span>
                    <span id="progress-percentage">0%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div id="progress-bar" class="bg-primary h-2.5 rounded-full" style="width: 0%"></div>
                </div>
            </div>

            <!-- 图片预览 -->
            <div id="preview-container" class="hidden mb-6">
                <h3 class="text-lg font-medium text-gray-800 mb-3">图片预览</h3>
                <div class="flex justify-center">
                    <img id="image-preview" src="" alt="预览图片" class="max-w-full max-h-96 object-contain border border-gray-200 rounded-lg shadow-sm"/>
                </div>
                <p id="file-info" class="text-sm text-gray-500 mt-2 text-center"></p>
            </div>

            <!-- 上传结果 -->
            <div id="result-container" class="hidden p-4 rounded-lg mb-6">
                <div class="flex items-start">
                    <div id="result-icon" class="mr-3 text-xl"></div>
                    <div>
                        <h3 id="result-title" class="font-medium text-lg mb-1"></h3>
                        <p id="result-message" class="text-gray-600"></p>
                    </div>
                </div>
            </div>

            <!-- 识别结果展示区域 -->
            <div id="recognition-result-container" class="hidden mb-6">
                <h3 class="text-lg font-medium text-gray-800 mb-4">识别结果</h3>
                
                <!-- 低置信度提示 -->
                <div id="low-confidence-alert" class="hidden bg-yellow-50 text-yellow-700 p-3 rounded-lg mb-4 flex items-center">
                    <i class="fa fa-exclamation-triangle mr-2"></i>
                    <span>识别结果置信度较低，仅供参考</span>
                </div>
                
                <!-- 首要识别结果 -->
                <div id="primary-result" class="mb-6 p-4 border border-gray-200 rounded-lg bg-gradient-to-br from-primary/5 to-white">
                    <div class="flex items-center mb-2">
                        <div class="bg-primary text-white text-xs px-2 py-1 rounded-full mr-2">首要结果</div>
                        <h4 id="primary-breed" class="text-lg font-bold text-gray-800">品种名称</h4>
                    </div>
                    <div class="flex items-center">
                        <div class="text-2xl font-bold text-primary mr-2"><span id="primary-confidence"></span>%</div>
                        <div class="text-sm text-gray-500">(置信度)</div>
                    </div>
                </div>
                
                <!-- 品种知识展示区域 -->
                <div id="breed-info-container" class="mb-6">
                    <h4 class="font-medium text-gray-700 mb-3">品种知识</h4>
                    <!-- 加载状态 -->
                    <div id="breed-info-loading" class="p-4 border border-gray-200 rounded-lg text-center">
                        <i class="fa fa-circle-o-notch fa-spin mr-2"></i>
                        <span>正在加载品种知识...</span>
                    </div>
                    <!-- 成功状态 -->
                    <div id="breed-info-content" class="hidden p-4 border border-gray-200 rounded-lg">
                        <!-- 特征标签 -->
                        <div class="mb-4">
                            <h5 class="text-sm font-medium text-gray-500 mb-2">特征标签</h5>
                            <div id="characteristic-tags" class="flex flex-wrap gap-2">
                                <!-- 动态添加标签 -->
                            </div>
                        </div>
                        <!-- 简要描述 -->
                        <div class="mb-4">
                            <h5 class="text-sm font-medium text-gray-500 mb-2">品种简介</h5>
                            <p id="breed-description" class="text-gray-700 line-clamp-3"></p>
                        </div>
                        <!-- 查看更多按钮 -->
                        <div class="text-center">
                            <button id="view-more-button" class="bg-secondary hover:bg-secondary/90 text-white font-medium px-4 py-2 rounded-lg inline-flex items-center shadow-sm hover:shadow transition-all-300">
                                <i class="fa fa-book mr-2"></i>查看更多
                            </button>
                        </div>
                    </div>
                    <!-- 错误状态 -->
                    <div id="breed-info-error" class="hidden p-4 border border-gray-200 rounded-lg bg-red-50 text-danger text-center">
                        <i class="fa fa-exclamation-circle mr-2"></i>
                        <span id="breed-info-error-message">品种详情加载失败</span>
                    </div>
                </div>
                
                <!-- Top-3 结果列表 -->
                <div class="mb-4">
                    <h4 class="font-medium text-gray-700 mb-3">相似品种</h4>
                    <div id="similar-breeds-list" class="space-y-3">
                        <!-- 相似品种项模板 -->
                        <!-- <div class="p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                            <div class="flex justify-between items-center">
                                <span class="text-gray-800">品种名称</span>
                                <span class="text-gray-600"><span>XX</span>%</span>
                            </div>
                        </div> -->
                    </div>
                </div>
            </div>

            <!-- 操作按钮区域 -->
            <div id="action-buttons" class="hidden flex justify-center space-x-4 mb-6">
                <button id="retry-button" class="bg-info hover:bg-info/90 text-white font-medium px-6 py-3 rounded-lg flex items-center shadow-md hover:shadow-lg transition-all-300">
                    <i class="fa fa-refresh mr-2"></i>重新上传
                </button>
                <button id="share-button" class="bg-secondary hover:bg-secondary/90 text-white font-medium px-6 py-3 rounded-lg flex items-center shadow-md hover:shadow-lg transition-all-300">
                    <i class="fa fa-share-alt mr-2"></i>分享结果
                </button>
            </div>

            <!-- 错误提示 -->
            <div id="error-container" class="hidden bg-red-50 text-danger p-4 rounded-lg mb-6">
                <div class="flex items-start">
                    <i class="fa fa-exclamation-circle text-xl mr-3 mt-0.5"></i>
                    <p id="error-message"></p>
                </div>
            </div>
        </section>
    </main>

    <footer class="bg-white shadow-sm py-6">
        <div class="container mx-auto px-4 text-center text-gray-600">
            <p>© 2023 宠物狗识别系统. 保留所有权利.</p>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.getElementById('file-input');
            const uploadArea = document.getElementById('upload-area');
            const uploadBtn = document.getElementById('upload-btn');
            const progressContainer = document.getElementById('progress-container');
            const progressBar = document.getElementById('progress-bar');
            const progressPercentage = document.getElementById('progress-percentage');
            const previewContainer = document.getElementById('preview-container');
            const imagePreview = document.getElementById('image-preview');
            const fileInfo = document.getElementById('file-info');
            const resultContainer = document.getElementById('result-container');
            const resultIcon = document.getElementById('result-icon');
            const resultTitle = document.getElementById('result-title');
            const resultMessage = document.getElementById('result-message');
            const errorContainer = document.getElementById('error-container');
            const errorMessage = document.getElementById('error-message');
            
            let selectedFile = null;
            
            // 上传区域点击事件
            uploadArea.addEventListener('click', function() {
                fileInput.click();
            });
            
            // 文件拖拽事件
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadArea.classList.add('border-primary');
                uploadArea.classList.add('bg-primary/5');
            });
            
            uploadArea.addEventListener('dragleave', function() {
                uploadArea.classList.remove('border-primary');
                uploadArea.classList.remove('bg-primary/5');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('border-primary');
                uploadArea.classList.remove('bg-primary/5');
                
                if (e.dataTransfer.files.length > 0) {
                    handleFileSelection(e.dataTransfer.files[0]);
                }
            });
            
            // 文件选择事件
            fileInput.addEventListener('change', function() {
                if (fileInput.files.length > 0) {
                    handleFileSelection(fileInput.files[0]);
                }
            });
            
            // 处理文件选择
            function handleFileSelection(file) {
                // 前端验证
                if (!validateFile(file)) {
                    return;
                }
                
                selectedFile = file;
                uploadBtn.disabled = false;
                
                // 显示预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    previewContainer.classList.remove('hidden');
                    fileInfo.textContent = `${file.name} (${formatFileSize(file.size)})`;
                };
                reader.readAsDataURL(file);
                
                // 隐藏之前的错误和结果
                errorContainer.classList.add('hidden');
                resultContainer.classList.add('hidden');
            }
            
            // 前端文件验证
            function validateFile(file) {
                // 验证文件类型
                const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
                if (!validTypes.includes(file.type)) {
                    showError('不支持的文件格式，仅支持 JPEG、PNG、WEBP');
                    return false;
                }
                
                // 验证文件大小
                const maxSize = 8 * 1024 * 1024; // 8MB
                const minSize = 10 * 1024; // 10KB
                
                if (file.size > maxSize) {
                    showError('文件大小不能超过 8MB，请压缩后重新上传');
                    return false;
                }
                
                if (file.size < minSize) {
                    showError('文件大小不能小于 10KB');
                    return false;
                }
                
                // 验证图片分辨率（可选，因为后端也会验证）
                // 这里简化处理，不返回Promise
                const img = new Image();
                const url = URL.createObjectURL(file);
                
                img.onload = function() {
                    URL.revokeObjectURL(url);
                    const minWidth = 50;
                    const minHeight = 50;
                    
                    if (img.width < minWidth || img.height < minHeight) {
                        showWarning('图片分辨率过低，可能影响识别效果，建议上传≥200×200px 的图片');
                    }
                };
                img.src = url;
                
                return true;
            }
            
            // 上传按钮点击事件
            uploadBtn.addEventListener('click', function() {
                if (selectedFile) {
                    uploadFile(selectedFile);
                }
            });
            
            // 上传文件到服务器
            function uploadFile(file) {
                // 显示进度条
                progressContainer.classList.remove('hidden');
                progressBar.style.width = '0%';
                progressPercentage.textContent = '0%';
                
                // 创建FormData
                const formData = new FormData();
                formData.append('file', file);
                
                // 创建XMLHttpRequest对象
                const xhr = new XMLHttpRequest();
                
                // 监听进度事件
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percent = Math.round((e.loaded / e.total) * 100);
                        progressBar.style.width = `${percent}%`;
                        progressPercentage.textContent = `${percent}%`;
                    }
                });
                
                // 监听完成事件
                xhr.addEventListener('load', function() {
                    progressContainer.classList.add('hidden');
                    
                    if (xhr.status === 200) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.code === 200 && response.data) {
                                // 上传成功
                                showSuccess('上传成功，正在进行犬种识别...', `文件ID: ${response.data.fileId}`);
                                
                                // 更新预览图片为服务器返回的URL
                                // 使用服务器返回的URL替换本地Blob URL以确保图片可以正确访问
                                imagePreview.src = response.data.url;
                                
                                // 保存文件信息用于后续可能的识别操作
                                sessionStorage.setItem('uploadedFileInfo', JSON.stringify({
                                    fileId: response.data.fileId,
                                    url: response.data.url,
                                    originalFilename: response.data.originalFilename,
                                    fileSize: response.data.fileSize,
                                    mimeType: response.data.mimeType
                                }));
                                
                                // 存储fileId到sessionStorage
                                sessionStorage.setItem('uploadedFileId', response.data.fileId);
                                sessionStorage.setItem('uploadedFileUrl', response.data.url);
                                
                                // 上传成功后，调用识别接口进行犬种识别
                                recognizeDogBreed(response.data.fileId);
                            } else {
                                showError(response.message || '上传失败');
                            }
                        } catch (error) {
                            showError('上传失败：响应格式错误');
                        }
                    } else if (xhr.status === 413) {
                        showError('文件大小不能超过 8MB，请压缩后重新上传');
                    } else if (xhr.status === 400) {
                        const response = JSON.parse(xhr.responseText);
                        showError(response.message || '上传失败：请求参数错误');
                    } else if (xhr.status === 503) {
                        showError('网络连接不稳定，上传失败，请检查网络后重试');
                        showRetryButton();
                    } else if (xhr.status === 500) {
                        const response = JSON.parse(xhr.responseText);
                        showError(response.message || '服务器内部错误，请联系管理员');
                    } else {
                        showError(`上传失败：HTTP错误 ${xhr.status}`);
                    }
                });
                
                // 监听错误事件
                xhr.addEventListener('error', function() {
                    progressContainer.classList.add('hidden');
                    showError('网络连接不稳定，上传失败，请检查网络后重试');
                    showRetryButton();
                });
                
                // 监听超时事件
                xhr.addEventListener('timeout', function() {
                    progressContainer.classList.add('hidden');
                    showError('上传超时，请检查网络后重试');
                    showRetryButton();
                });
                
                // 设置超时时间（30秒）
                xhr.timeout = 30000;
                
                // 发送请求
                xhr.open('POST', '/api/v1/upload/image');
                xhr.send(formData);
            }
            
            // 显示错误消息
            function showError(message) {
                errorMessage.textContent = message;
                errorContainer.classList.remove('hidden');
                resultContainer.classList.add('hidden');
            }
            
            // 显示警告消息（用于分辨率低的情况，但仍然允许上传）
            function showWarning(message) {
                // 创建临时警告提示
                const warningElement = document.createElement('div');
                warningElement.className = 'bg-yellow-50 text-yellow-700 p-3 rounded-lg mb-4 flex items-center animate-fade-in';
                warningElement.innerHTML = `
                    <i class="fa fa-exclamation-triangle mr-2"></i>
                    <span>${message}</span>
                `;
                
                uploadArea.parentNode.insertBefore(warningElement, uploadArea.nextSibling);
                
                // 3秒后自动隐藏
                setTimeout(() => {
                    warningElement.classList.add('opacity-0', 'transition-opacity', 'duration-500');
                    setTimeout(() => {
                        warningElement.remove();
                    }, 500);
                }, 3000);
            }
            
            // 显示成功消息
            function showSuccess(title, message) {
                resultIcon.className = 'fa fa-check-circle text-secondary';
                resultTitle.textContent = title;
                resultTitle.className = 'font-medium text-lg mb-1 text-secondary';
                resultMessage.textContent = message;
                resultContainer.classList.remove('hidden');
                errorContainer.classList.add('hidden');
            }
            
            // 显示重试按钮
            function showRetryButton() {
                uploadBtn.innerHTML = '<i class="fa fa-refresh mr-2"></i>重试';
                uploadBtn.classList.remove('bg-primary');
                uploadBtn.classList.add('bg-info');
                uploadBtn.disabled = false;
            }
            
            // 犬种识别功能
            function recognizeDogBreed(fileId) {
                // 创建XMLHttpRequest对象
                const xhr = new XMLHttpRequest();
                
                // 监听完成事件
                xhr.addEventListener('load', function() {
                    if (xhr.status === 200) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            
                            // 检查数据格式
                            if (!response || !response.data) {
                                showError('服务器返回数据格式异常，请刷新页面重试');
                                showActionButtons(false); // 仅显示重试按钮
                                return;
                            }
                            
                            const recognitionData = response.data;
                            
                            if (recognitionData.success && recognitionData.results && recognitionData.results.length > 0) {
                                // 识别成功，展示结果
                                displayRecognitionResults(recognitionData);
                            } else {
                                // 识别失败
                                showError(recognitionData.message || '识别失败，请重新上传图片');
                                showActionButtons(false); // 仅显示重试按钮
                            }
                        } catch (error) {
                            showError('服务器返回数据格式异常，请刷新页面重试');
                            showActionButtons(false); // 仅显示重试按钮
                        }
                    } else if (xhr.status === 400) {
                        const response = JSON.parse(xhr.responseText);
                        showError(response.message || '识别失败：请求参数错误');
                        showActionButtons(false); // 仅显示重试按钮
                    } else if (xhr.status === 404) {
                        showError('未找到识别结果，请确认文件ID是否正确');
                        showActionButtons(false); // 仅显示重试按钮
                    } else {
                        showError('网络连接不稳定，获取结果失败，请重试');
                        showActionButtons(false); // 仅显示重试按钮
                    }
                });
                
                // 监听错误事件
                xhr.addEventListener('error', function() {
                    showError('网络连接不稳定，获取结果失败，请重试');
                    showActionButtons(false); // 仅显示重试按钮
                });
                
                // 监听超时事件
                xhr.addEventListener('timeout', function() {
                    showError('获取结果超时，请检查网络后重试');
                    showActionButtons(false); // 仅显示重试按钮
                });
                
                // 设置超时时间（10秒）
                xhr.timeout = 10000;
                
                // 发送请求
                xhr.open('GET', `/api/v1/identification/result/${fileId}`);
                xhr.send();
            }
            
            // 展示识别结果
            function displayRecognitionResults(data) {
                // 隐藏错误提示，显示结果区域
                errorContainer.classList.add('hidden');
                recognitionResultContainer.classList.remove('hidden');
                
                // 检查是否需要显示低置信度提示
                const lowConfidenceAlert = document.getElementById('low-confidence-alert');
                if (data.lowConfidence || (data.results && data.results.length > 0 && data.results[0].confidence < 0.6)) {
                    lowConfidenceAlert.classList.remove('hidden');
                } else {
                    lowConfidenceAlert.classList.add('hidden');
                }
                
                // 显示首要结果
                if (data.results && data.results.length > 0) {
                    const primaryResult = data.results[0];
                    document.getElementById('primary-breed').textContent = primaryResult.breedName || '未知品种';
                    document.getElementById('primary-confidence').textContent = Math.round((primaryResult.confidence || 0) * 100);
                    
                    // 显示Top-3相似品种
                    const similarBreedsList = document.getElementById('similar-breeds-list');
                    similarBreedsList.innerHTML = '';
                    
                    // 从第二个结果开始显示（跳过首要结果）
                    for (let i = 1; i < data.results.length && i < 3; i++) {
                        const breed = data.results[i];
                        const breedItem = createBreedListItem(breed);
                        similarBreedsList.appendChild(breedItem);
                    }
                    
                    // 如果没有足够的相似品种，显示提示
                    if (similarBreedsList.children.length === 0) {
                        const emptyItem = document.createElement('div');
                        emptyItem.className = 'text-gray-500 italic text-center py-3';
                        emptyItem.textContent = '暂无其他相似品种';
                        similarBreedsList.appendChild(emptyItem);
                    }
                }
                
                // 显示操作按钮
                showActionButtons(true);
                
                // 异步获取并显示品种知识
                 if (data.results && data.results.length > 0 && data.results[0].breed_id) {
                     fetchBreedInfo(data.results[0].breed_id);
                 }
            }
            
            // 获取并显示品种知识
            function fetchBreedInfo(breedId) {
                // 验证breedId
                if (!breedId || typeof breedId !== 'number' || breedId <= 0) {
                    displayBreedInfoError('无效的品种ID');
                    return;
                }
                
                // 显示加载状态
                const elements = window.breedInfoElements;
                elements.container.style.display = 'block';
                elements.loading.style.display = 'block';
                elements.content.style.display = 'none';
                elements.error.style.display = 'none';
                
                // 创建XHR请求
                const xhr = new XMLHttpRequest();
                const url = `/api/v1/breed/info/${breedId}`;
                
                xhr.open('GET', url, true);
                xhr.timeout = 2000; // 2秒超时
                
                xhr.onload = function() {
                    elements.loading.style.display = 'none';
                    
                    if (xhr.status === 200) {
                        try {
                            const breedInfo = JSON.parse(xhr.responseText);
                            displayBreedInfo(breedInfo, breedId);
                        } catch (e) {
                            displayBreedInfoError('数据解析错误');
                        }
                    } else if (xhr.status === 404) {
                        displayBreedInfoError('未找到该品种的详细信息');
                    } else {
                        displayBreedInfoError('品种详情加载失败');
                    }
                };
                
                xhr.onerror = function() {
                    elements.loading.style.display = 'none';
                    displayBreedInfoError('网络连接失败，请检查您的网络连接');
                };
                
                xhr.ontimeout = function() {
                    elements.loading.style.display = 'none';
                    displayBreedInfoError('品种详情加载失败，请求超时');
                };
                
                xhr.send();
            }
            
            // 显示品种知识
            function displayBreedInfo(breedInfo, breedId) {
                const elements = window.breedInfoElements;
                
                // 显示内容，隐藏错误
                elements.content.style.display = 'block';
                elements.error.style.display = 'none';
                
                // 处理特征标签
                const tags = breedInfo.characteristic_tags || ['待补充'];
                elements.tags.innerHTML = '';
                
                tags.forEach(tag => {
                    const tagElement = document.createElement('span');
                    tagElement.className = 'px-2 py-1 bg-blue-50 text-blue-600 text-xs rounded-full';
                    tagElement.textContent = tag;
                    elements.tags.appendChild(tagElement);
                });
                
                // 处理描述
                elements.description.textContent = breedInfo.description || '暂无该品种的详细描述信息';
                
                // 设置查看更多按钮的点击事件
                elements.viewMoreButton.onclick = function() {
                    // 跳转到品种百科详情页
                    window.location.href = `/breed/wiki/${breedId}`;
                };
            }
            
            // 显示品种知识错误
            function displayBreedInfoError(message) {
                const elements = window.breedInfoElements;
                elements.content.style.display = 'none';
                elements.error.style.display = 'block';
                elements.errorMessage.textContent = message || '品种详情加载失败';
            }
            
            // 创建品种列表项
            function createBreedListItem(breed) {
                const item = document.createElement('div');
                item.className = 'p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors';
                
                item.innerHTML = `
                    <div class="flex justify-between items-center">
                        <span class="text-gray-800">${breed.breedName || '未知品种'}</span>
                        <span class="text-gray-600"><span>${Math.round((breed.confidence || 0) * 100)}</span>%</span>
                    </div>
                `;
                
                return item;
            }
            
            // 显示操作按钮
            function showActionButtons(showShareButton) {
                const actionButtons = document.getElementById('action-buttons');
                const retryButton = document.getElementById('retry-button');
                const shareButton = document.getElementById('share-button');
                
                actionButtons.classList.remove('hidden');
                
                // 配置按钮显示
                if (showShareButton) {
                    shareButton.classList.remove('hidden');
                } else {
                    shareButton.classList.add('hidden');
                    // 如果只显示重试按钮，居中显示
                    actionButtons.classList.add('justify-center');
                }
            }
            
            // 格式化文件大小
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            // 初始化页面
            function initPage() {
                // 获取DOM元素引用
                recognitionResultContainer = document.getElementById('recognition-result-container');
                actionButtons = document.getElementById('action-buttons');
                
                // 品种知识相关DOM元素
                const breedInfoContainer = document.getElementById('breed-info-container');
                const breedInfoLoading = document.getElementById('breed-info-loading');
                const breedInfoContent = document.getElementById('breed-info-content');
                const breedInfoError = document.getElementById('breed-info-error');
                const breedInfoErrorMessage = document.getElementById('breed-info-error-message');
                const characteristicTags = document.getElementById('characteristic-tags');
                const breedDescription = document.getElementById('breed-description');
                const viewMoreButton = document.getElementById('view-more-button');
                
                // 保存全局引用
                window.breedInfoElements = {
                    container: breedInfoContainer,
                    loading: breedInfoLoading,
                    content: breedInfoContent,
                    error: breedInfoError,
                    errorMessage: breedInfoErrorMessage,
                    tags: characteristicTags,
                    description: breedDescription,
                    viewMoreButton: viewMoreButton
                };
                
                // 重新上传按钮事件监听
                document.getElementById('retry-button').addEventListener('click', function() {
                    // 重置页面状态
                    resetPage();
                });
                
                // 分享按钮事件监听
                document.getElementById('share-button').addEventListener('click', function() {
                    // 这里可以实现分享功能
                    alert('分享功能开发中');
                });
                
                // 检查是否有上次上传的文件信息
                const lastFileId = sessionStorage.getItem('uploadedFileId');
                if (lastFileId) {
                    // 询问用户是否要查看上次的识别结果
                    if (confirm('检测到您有未查看的识别结果，是否立即查看？')) {
                        recognizeDogBreed(lastFileId);
                    }
                }
            }
            
            // 重置页面状态
            function resetPage() {
                // 隐藏结果和错误提示
                recognitionResultContainer.classList.add('hidden');
                errorContainer.classList.add('hidden');
                resultContainer.classList.add('hidden');
                actionButtons.classList.add('hidden');
                
                // 重置上传按钮
                uploadBtn.innerHTML = '<i class="fa fa-paper-plane mr-2"></i>开始上传';
                uploadBtn.classList.remove('bg-info');
                uploadBtn.classList.add('bg-primary');
                uploadBtn.disabled = true;
                
                // 清空文件选择
                selectedFile = null;
                fileInput.value = '';
                
                // 隐藏预览
                previewContainer.classList.add('hidden');
                imagePreview.src = '';
                
                // 重置品种知识区域
                const breedInfoElements = window.breedInfoElements;
                if (breedInfoElements) {
                    breedInfoElements.container.style.display = 'none';
                    breedInfoElements.loading.style.display = 'none';
                    breedInfoElements.content.style.display = 'none';
                    breedInfoElements.error.style.display = 'none';
                }
                
                // 移除存储的文件信息
                sessionStorage.removeItem('uploadedFileId');
                sessionStorage.removeItem('uploadedFileUrl');
                sessionStorage.removeItem('uploadedFileInfo');
            }
            // 初始化全局变量
            let recognitionResultContainer = null;
            let actionButtons = null;
        });
    </script>
</div>
</section>
</main>
</body>
</html>